#!/usr/bin/env python3
# #-*- coding: UTF-8 -*- 

import socket
import time
import numpy as np
import subprocess
import threading
from client_func import client

cmds = {"detect_laser" : "python3 /home/pi/workspace/stereo-cv/scripts/clientA/client.py"}

def server_thread(cmd):
    client()
    # p = subprocess.Popen(cmds[cmd], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    # # p.wait()
    # # print(p.stdout.read().decode())
    # for line in iter(p.stdout.readline, b''):
    #     print(line.decode())
    #     pass
    # p.stdout.close()
    # p.wait()

try:
    HOST = '169.254.80.102'
    PORT = 8000
    ADDRESS = (HOST, PORT)
    # 创建一个套接字
    tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定本地ip
    tcpServer.bind(ADDRESS)
    # 开始监听
    tcpServer.listen(5)

    while True:
        print("wait for connecting......")
        client_socket, client_address = tcpServer.accept()
        print("succeed connedted!")

        while True:
            data = client_socket.recv(1024)
            if data:
                client_socket.send(b"ok")
                print(data.decode())
                t = threading.Thread(target=server_thread, args=(data.decode(),))
                t.start()
            else:
               print("Disconnected!")
               break
            
except:
    import traceback
    traceback.print_exc()
finally:
    print("\n\nFinished\n\n")